<template>
  <el-card>
    <template #header>
      <PlusSearch
        v-model="state"
        :columns="searchColumns"
        :show-number="2"
        label-width="80"
        label-position="right"
        @change="handleChange"
        @search="handleSearch"
        @reset="handleRest"
      />
    </template>
    <el-alert
      title="TODO:数据状态显示；按反馈时间先后排序"
      type="info"
      :closable="false"
    />
    <pure-table
      adaptive
      :adaptiveConfig="adaptiveConfig"
      :data="tableData"
      :columns="columns"
      stripe
    >
      <template #operation="{ row }">
        <el-button link type="primary" size="default" @click="handleClick(row)">
          查看详情
        </el-button>
      </template>
    </pure-table>
    <el-pagination
      small
      background
      right
      layout="prev, pager, next"
      :page-count="totalPage"
      :page-size="pageSize"
      class="mt-4"
      @current-change="handlePageChange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { onBeforeRouteUpdate, useRouter } from "vue-router";
import { getFeedbackListDetail, getFeedbackTotalPage } from "@/api/feedback";
import { ref, onMounted, onUpdated } from "vue";
import "plus-pro-components/es/components/search/style/css";
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import { useFeedbackInfoStoreHook } from "@/store/modules/feedbackInfo";
import { format } from "date-fns";
import { useColumns } from "./columns";
import { getAqiMap } from "@/api/aqi";
import { aqiFeedbackType, aqiType, monitorType } from "@/store/types";
import { listProvinces, getGridCityByProvinceId } from "@/api/province";
import { getAqiMeasuredDetailByFbId } from "@/api/aqiMeasuredResult";
import {
  pcTextArr,
  provinceAndCityData,
  codeToText
} from "element-china-area-data";

defineOptions({
  name: "Feedback"
});

const tableData = ref([]);
const totalPage = ref(1);
const pageSize = ref(10);
const pageNum = ref(1);
const router = useRouter();
const { columns } = useColumns();
const aqiFeedbackParam = ref({});

const getProvinceList = async () => {
  try {
    const { data } = await listProvinces();
    console.log("provinces");
    console.log(data);
    const provinces = data.map(province => ({
      value: province.provinceId,
      label: province.provinceName,
      children: []
    }));
    for (const province of provinces) {
      const cityData = (await getGridCityByProvinceId(province.value)).data;
      const cities = cityData.map(city => ({
        value: city.cityId,
        label: city.cityName
      }));
      // 将城市信息添加到对应省份的children属性中
      province.children = cities;
      console.log(province, "children");
    }
    return provinces;
  } catch (e) {
    console.log(e);
  }
};

const searchColumns: PlusColumn[] = [
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "未指派",
        value: "0"
      },
      {
        label: "已指派",
        value: "1"
      }
    ]
  },
  {
    label: "反馈者ID",
    prop: "monId",
    valueType: "copy"
  },
  {
    label: "反馈编号",
    prop: "fbId",
    valueType: "input"
  },
  {
    label: "反馈时间",
    prop: "fbTime",
    valueType: "date-picker",
    fieldProps: {
      type: "daterange",
      startPlaceholder: "请选择",
      endPlaceholder: "请选择"
    }
  },
  {
    label: "反馈省市",
    prop: "province",
    valueType: "cascader",
    options: getProvinceList()
  },
  {
    label: "反馈地址",
    prop: "fbAdddress",
    valueType: "input"
  }
];
const aqiTagMap = ref<aqiType[]>([]);

const getAqiTagMap = async () => {
  try {
    const { data } = await getAqiMap();
    aqiTagMap.value = data;
  } catch (e) {
    console.log(e);
  }
};

function getAqi(aqiLevel: number) {
  return aqiTagMap.value.find((item: aqiType) => item.aqiLevel === aqiLevel);
}

const getTableData = async () => {
  try {
    console.log(aqiFeedbackParam.value, "aqiFeedbackParam");
    const { data } = await getFeedbackListDetail({
      aqiFeedbackParam: aqiFeedbackParam.value,
      pageSize: pageSize.value,
      pageNum: pageNum.value
    });
    data.list.forEach(
      (item: {
        aqiFeedback: aqiFeedbackType;
        monitor: monitorType;
        imageUrl: string;
      }) => {
        item.aqiFeedback.fbTime = format(
          new Date(item.aqiFeedback.fbTime),
          "yyyy-MM-dd HH:mm:ss"
        );
        item.aqiFeedback.remarks = getAqi(item.aqiFeedback.fbAqiLevel);
      }
    );
    tableData.value = data.list;
  } catch (e) {
    console.log(e);
  }
};

const getTableTotalPage = async () => {
  try {
    const total = await getFeedbackTotalPage({
      aqiFeedbackParam: aqiFeedbackParam.value,
      pageSize: pageSize.value
    });
    totalPage.value = total.data;
  } catch (e) {
    console.log(e);
  }
};

onMounted(() => {
  getAqiTagMap().then(() => {
    getTableData();
    getTableTotalPage();
  });
});

//search from
const state = ref({
  status: "0",
  time: new Date().toString()
});

const handleChange = (values: any) => {
  console.log(values, "change");
};
const handleSearch = (values: any) => {
  let provinceId = values.province?.[0] ?? null;
  let cityId = values.province?.[1] ?? null;
  let fbStartTime = values.fbTime?.[0] ?? null;
  let fbEndTime = values.fbTime?.[1] ?? null;
  let monId = values.monId ?? null;
  let fbAssignState = values.status ?? null;
  let fbAddress = values.fbAdddress ?? null;
  aqiFeedbackParam.value = {
    provinceId,
    cityId,
    fbStartTime,
    fbEndTime,
    monId,
    fbAssignState,
    fbAddress
  };
  getTableData();
  getTableTotalPage();
};
const handleRest = () => {
  aqiFeedbackParam.value = {};
  getTableData();
  getTableTotalPage();
};

//分页
const handlePageChange = (currentPage: number) => {
  pageNum.value = currentPage;
  getTableData();
};

//表格大小自适应
const adaptiveConfig: AdaptiveConfig = {
  /** 表格距离页面底部的偏移量，默认值为 `96` */
  offsetBottom: 85,
  /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
  fixHeader: true
};

const getResult = async (fbId: number) => {
  const { data } = await getAqiMeasuredDetailByFbId(fbId);
  console.log(data, "result");
  console.log(data.aqiValue, "result1111111");
  return data;
};
getResult(1);

//选中
const handleClick = async (row: any) => {
  console.log(row, "click");
  useFeedbackInfoStoreHook().SET_AQIFEEDBACK(row.aqiFeedback);
  useFeedbackInfoStoreHook().SET_MONITOR(row.monitor);
  useFeedbackInfoStoreHook().SET_IMAGEURL(row.imageUrl);
  useFeedbackInfoStoreHook().SET_AQI(row.aqi);
  console.log(row.aqiFeedback.fbId, "fbId");
  if (row.aqiFeedback.fbAssignState == 1) {
    const result = await getResult(row.aqiFeedback.fbId);
    console.log(result, "result");
    useFeedbackInfoStoreHook().SET_AQIVALUE(result.aqiValue);
    useFeedbackInfoStoreHook().SET_RESULT(result.aqiMeasuredResult);
    useFeedbackInfoStoreHook().SET_INSPECTOR(result.inspector);
  }
  router.push("/feedbackInfo/index");
};
</script>

<style>
/* 此处样式会在全局都生效，上面 tableRowClassName 函数返回的值也就是类名必须在全局中唯一，避免样式突出 */
.pure-warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.pure-success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
